package com.xz.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;

/**
 * @author shafulin
 * @date 2023/4/19 9:41
 * @description 请求流转换为多次读取的请求流 过滤器
 * 参考文档：https://mp.weixin.qq.com/s?__biz=MzI3ODcxMzQzMw==&mid=2247582237&idx=1&sn=55dde73d6fa87a5c2cec7d559df1ee4f&chksm=eb51072bdc268e3dc6827d7f6b299d46654ca6cfb3d5334e01e33bd997fcbae060f41674c407&mpshare=1&scene=1&srcid=04170MjxrcAqeubcSdWP0D46&sharer_sharetime=1681703068327&sharer_shareid=cb83a8a406e38d7526ca4f2fc44eeb13&key=93e34dd7a4c876e2a5c05cbc004181eb9e3b84aa43f37d6989e589feefc347e11375334c66f1b7b78e479dbf32f35015c24ac54fdb0bee687352cddb32137adbaae763b04e1d9701d98d5f6d082faab69bf17da51cbf75cfebaf7601d44528b8df16fe60becd6f6508243973e2b32799ac11815b1b3c35abbd7639d69648fa32&ascene=1&uin=MTMwMTQxOTA3Mg%3D%3D&devicetype=Windows+10+x64&version=63090217&lang=zh_CN&countrycode=CN&exportkey=n_ChQIAhIQWSG9aHYI5p3LdyxBRtV9URLqAQIE97dBBAEAAAAAAG8sDxnH8VIAAAAOpnltbLcz9gKNyK89dVj07Z13pBEITcyiYH8qDOx%2B5OrXsIu8V3PjBSe7EOcu3OrGa9wZhTIo9%2Bzl%2F59wPs%2B72EpzTUod2K2gx9FsXSThdQZZkEK0E20V3p7p4fZ84aBkiBwjsjMUx6XMy9ERsq25KZ8FGjYY48TjtFEBnINIAbJ8sSLqoB%2FowuCs096I424JDMheqgHE6nwYr1BkLaRaHmzIeS4FOuseGdCF0pzzqPUAoip3wkNxK8v5K%2BFKbkKTI%2BSi2HMfytzQIyk4MzfC%2BdUrlg%3D%3D&acctmode=0&pass_ticket=NlvpRmUeTQsJstpjatgV5QF%2FF31P2bL%2FL5bYVaJOstcsQa3bpEdt8FbbwHINZl24oWGdTi%2FFKvzpWGPZoX5bjQ%3D%3D&wx_header=1&fontgear=2
 */
@Slf4j
@Component
@Order(HIGHEST_PRECEDENCE + 1)  // 优先级最高
public class HttpServletRequestInputStreamFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //log.info("过滤器-请求流转换为多次读取的请求流");
        // 转换为可以多次获取流的request
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        InputStreamHttpServletRequestWrapper inputStreamHttpServletRequestWrapper = new InputStreamHttpServletRequestWrapper(httpServletRequest);

        // 放行
        chain.doFilter(inputStreamHttpServletRequestWrapper, response);
    }
}
